package eerbaar.shared.persist.internal.lib;

import eerbaar.position.IPosition;
import eerbaar.position.PositionFactory;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.tree.IAttributes;
import eerbaar.shared.tree.INode;

public class PositionPersister implements IPersister<IPosition> {

    private IPosition target;

    public PositionPersister() {
        //
    }

    public PositionPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    public PositionPersister(IPosition wrapper) {
        this.target = wrapper;
    }

    @Override
    public Class<IPosition> getRegistertedInterface() {
        return IPosition.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        return new ISaver[] {};
    }

    @Override
    public String getSavableName() {

        return "position";
    }

    @Override
    public IPosition getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> rsist) {
        return false;
    }

    @Override
    public IPosition load(INode node) {
        assert (node != null);

        IAttributes attributes = node.getAttributes();
        int x = attributes.get(Integer.class, "x");
        int y = attributes.get(Integer.class, "y");
        this.target = PositionFactory.createPosition(x, y);

        return this.target;
    }

    @Override
    public void saveAttributes(INode node) {

        IAttributes a = node.getAttributes();
        a.set(Integer.class, "x", this.target.getX());
        a.set(Integer.class, "y", this.target.getY());
    }

    @Override
    public void setTarget(IPosition obj) {
        this.target = obj;
    }

}
